package com.jason.apps.dashboard;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.R;
import com.jason.apps.alert.AlertDialogFragment;
import com.jason.apps.alert.EmptyAlert;
import com.jason.apps.alert.ErrorAlert;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

@SuppressLint("ParserError")
public class AddPanoramaImage extends SherlockFragment implements OnItemSelectedListener  {
	
	public EditText panorama;
	public ImageButton map;
	public Button addpano;
	public Spinner property;
		
	String host = "property-portal.uphero.com";
	String ftpuser = "a5596663";
	String ftppass = "ranger123";
	String saveLocation = "/public_html";
	String folderLocation = "/image/";
	List<String> labels = new ArrayList<String>();
	List<Integer> ids = new ArrayList<Integer>();
	int propertyId=-1;
	
	FTPClient con = null;
	public final String KEY_ID = "property_id";
	public final String KEY_NAME = "property_name";
	
	SherlockFragmentActivity fa;
	ConsumeWebService consume=new ConsumeWebService();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.addpanorama, container, false);
		fa = (SherlockFragmentActivity) super.getActivity();
		
		 panorama=(EditText)view.findViewById(R.id.panorama);
		 addpano=(Button)view.findViewById(R.id.addpano);
		 property=(Spinner)view.findViewById(R.id.propertyspinner);
		 
		 new setItem().execute();
		 
		 addpano.setOnClickListener(new View.OnClickListener() {
		
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!(panorama.getText().toString().trim().equals(""))){
					new AddAmm().execute();
				}
				else{
					FragmentManager fm = getActivity().getSupportFragmentManager();
				     EmptyAlert alert = new EmptyAlert();
				     alert.show(fm, "Alert_Dialog");
				}
			}
		});
	
		
		return view;
    }
	public void setUrl(String url){
		panorama.setText(url);
	}
	public void loadSpinner(Spinner property){

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, labels);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        property.setAdapter(dataAdapter);
        property.setOnItemSelectedListener(this);

	}
	public List<String> getAllLabels(){
	       // List<String> labels = new ArrayList<String>();
	 
	        String data = consume.getAllProperty();
			 
			 try {
				 	labels.add("None");
				 	ids.add(0);
				 	
					JSONArray array = new JSONArray(data);
					
					for (int i = 0; i < array.length(); i++) {
						//personsName=new HashMap<String, String>();
						JSONObject e = array.getJSONObject(i);
						labels.add(e.getString(KEY_NAME));
						ids.add(e.getInt(KEY_ID));
					}
					
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
				}finally{
					
				}
	        
	        return labels;
	    }
	
	//Asynctask
	@SuppressLint({ "NewApi", "NewApi" })
	public class AddAmm extends AsyncTask<Void, Void, Void> {

	    private final ProgressDialog dialog = new ProgressDialog(fa);

	    protected void onPreExecute() {

	            this.dialog.setMessage("Loading...");
	            this.dialog.show();
	    }


	    protected Void doInBackground(final Void... unused) {
	    	
	    	String file=panorama.getText().toString();
	    	String filename=new File(file).getName();
	    	con = new FTPClient();
	    	
	    		    	
			try {
								
											
					boolean results=consume.addPanorama("http://"+host+folderLocation+filename, propertyId);
						if(results){
							con.connect(host);
								
							con.login(ftpuser, ftppass);
							System.out.println("Nesud");
							
							con.enterLocalPassiveMode(); // important!
							con.setFileType(FTP.BINARY_FILE_TYPE);
							
							BufferedInputStream buffIn = null;
							buffIn = new BufferedInputStream(
							new FileInputStream(new File(file)));

							boolean result = con.storeFile(saveLocation
							+ folderLocation + filename, buffIn);
							buffIn.close();
							
							if (result)
								Log.v("upload result", "succeeded");
							con.logout();
							con.disconnect();
							
							FragmentManager fm = getActivity().getSupportFragmentManager();									                
			                AlertDialogFragment alert = new AlertDialogFragment();
			                
			                alert.show(fm, "Alert_Dialog");
						}
						else{
							Log.v("upload result", "failed jud");
							FragmentManager fm = getActivity().getSupportFragmentManager();									                
			                ErrorAlert alert = new ErrorAlert();
			                alert.show(fm, "Alert_Dialog");
						}
						
			} catch (Exception e) {
				Log.e("",e.toString());
			}
				    	
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
		    panorama.setText("");
	    	if (this.dialog!=null) {
	            this.dialog.dismiss();
	            }  
	     }
	  }
	
	//Asynctask
	public class setItem extends AsyncTask<Void, Void, Void> {

	    private final ProgressDialog dialog = new ProgressDialog(fa);

	    protected void onPreExecute() {

	            this.dialog.setMessage("Loading...");
	            this.dialog.show();
	    }

	    protected Void doInBackground(final Void... unused) {
	    	labels.clear();
	    	getAllLabels();
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
	    	loadSpinner(property);
	    	if (this.dialog!=null) {
	            this.dialog.dismiss();
	            }  
	     }
	  }

	public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		propertyId=ids.get(position);
	}
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}


}